package cn.com.taiji.oospub.wechat.controller.nutrition;


import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.oospub.wechat.common.Finals;
import cn.com.taiji.oospub.wechat.common.ObjectToXML;
import cn.com.taiji.oospub.wechat.common.tool.DoubleTools;
import cn.com.taiji.oospub.wechat.common.tool.TimeTools;
import cn.com.taiji.oospub.wechat.common.util.HttpUtil;
import cn.com.taiji.oospub.wechat.controller.BaseLogController;
import cn.com.taiji.oospub.wechat.entity.*;
import cn.com.taiji.oospub.wechat.model.CardConsumptionModel;
import cn.com.taiji.oospub.wechat.service.*;
import cn.com.taiji.pub.StringTools;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

//
///**
// * 营养控制层
// * @author fan
// *
// */
@Controller
@RequestMapping("/wx/nutrition")
public class NutritionController extends BaseLogController {
    @Autowired
    private ICourseNutritionService courseNutritionManager;
    @Autowired
    private ICoursesOrdersDetailsService coursesOrdersDetailsManager;
    @Autowired
    private ICoursesService coursesManager;
    @Autowired
    private IStandardService standardManager;
    @Autowired
    private IOrderOfDaynutService orderOfDaynutManager;
    @Autowired
    private IConfigOrderTimeService configOrderTimeManager;
    @Autowired
    private IMemberBmiService memberBmiService;
    @Autowired
    private IMemberBaseInfoService memberBaseInfoService;
    @Autowired
    private ICoursesImgService coursesImgService;
    @Autowired
    private ICoursesService coursesService;
    @Autowired
    private ISchoolBaseInfoService schoolBaseInfoService;

    @Value("${kongxc_pos_http_server_url}")
    private String kongxc_pos_http_server_url;
    @Value("${PROPASS}")
    public String PROPASS;
    @Value("${PROJECT_CODE}")
    public String PROJECT_CODE;
    @Value("${CUS_NAME}")
    public String CUS_NAME;

    /**
     * 今日营养分析
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/analysis", method = RequestMethod.GET)
    @ResponseBody
    public String analysisGet(Model model, HttpServletRequest request, HttpServletResponse response) {
        String par = request.getParameter("par");
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        model.addAttribute("member", member);
        if (member.getWeightId() == null) {
            model.addAttribute("result", false);
            model.addAttribute("message", "请完善体重信息");
            return JSONObject.toJSONString(model);
        } else if (member.getHeight() == null) {
            model.addAttribute("result", false);
            model.addAttribute("message", "请完善身高信息");
            return JSONObject.toJSONString(model);
        } else if (member.getActive() == null) {
            model.addAttribute("result", false);
            model.addAttribute("message", "请完善活动强度信息");
            return JSONObject.toJSONString(model);
        }

        //查询对应身体参数标准值
        QueryWrapper<Standard> standardModel = new QueryWrapper<>();
        DecimalFormat df = new DecimalFormat("######0.00");
        //--------体重-------
        if (member.getWeightId() != null) {
            standardModel.between("WEIGHT-" + member.getWeightId().intValue(), -1, 1);
        }
        //--------年龄-------
        if (member.getUserAge() != null) {
            standardModel.between("AGE-" + member.getUserAge().intValue(), -1, 1);
        }
        //--------身高-------
        if (member.getHeight() != null) {
            standardModel.between("HEIGHT-" + member.getHeight().intValue(), -1, 1);
        }
        //--------运动强度-------
        if (member.getHeight() != null) {
            standardModel.eq("ACTIVE", member.getActive());
        }

        List<Standard> nutList = standardManager.list(standardModel);
        Standard standard = null;
        if (nutList != null && nutList.size() > 0) {
            standard = nutList.get(0);
        } else {
            standard = new Standard();
            standard.setHot(0.0);
            standard.setProtein(0.0);
            standard.setSodium(0.0);
            standard.setFat(0.0);
            standard.setCarbon(0.0);
            standard.setFiler(0.0);
        }
        model.addAttribute("zhOrEn", Finals.ZhOrEn.values());
        model.addAttribute("member", member);

        //查询当天有效订单
        QueryWrapper<CoursesOrdersDetails> queryModel = new QueryWrapper<>();
        queryModel.ge("last_changed", LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
        queryModel.le("last_changed", LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
        queryModel.eq("is_effective", true);
        queryModel.eq("is_refunding", 0);
        queryModel.eq("creator", member.getId());
        List<CoursesOrdersDetails> list = coursesOrdersDetailsManager.queryList(queryModel);
        Courses courses;
        Double NL = 0.0, TSHHW = 0.0, SSXW = 0.0, DBZ = 0.0, ZF = 0.0, NLTotal = 0.0, SSXWTotal = 0.0, DBZTotal = 0.0, ZFTotal = 0.0, CSHHWTotal = 0.0;
        Double biaozhunNL = 0.0, biaozhunDDZ = 0.0, biaozhunNA = 0.0, biaozhunZF = 0.0, biaozhunTS = 0.0, biaozhunXW = 0.0;
        Double XW = 0.0, XWTotal = 0.0;
        if (list != null && list.size() > 0) {

            //计算今日摄入营养总量
            for (CoursesOrdersDetails cod : list) {
                NL = 0.0;
                TSHHW = 0.0;
                SSXW = 0.0;
                DBZ = 0.0;
                ZF = 0.0;
                Map<String, Double> nutMap = new TreeMap<String, Double>(new Comparator<String>() {
                    @Override
                    public int compare(String obj1, String obj2) {
                        return obj1.compareTo(obj2);
                    }
                });
                if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                    nutMap.put("Kilocalorie", 0.0);
                    nutMap.put("Sodium", 0.0);
                    nutMap.put("Protein", 0.0);
                    nutMap.put("Fats", 0.0);
                    nutMap.put("Carbohydrate", 0.0);
                } else {
                    nutMap.put("能量", 0.0);
                    nutMap.put("钠", 0.0);
                    nutMap.put("蛋白质", 0.0);
                    nutMap.put("脂肪", 0.0);
                    nutMap.put("碳水化合物", 0.0);
                }

                courses = coursesManager.findById(cod.getCourseId());
                //--------查询菜品主图开始----------
                QueryWrapper<CoursesImg> coursesImgModel = new QueryWrapper<>();
                coursesImgModel.eq("course_pos_no", courses.getPosNo());
                coursesImgModel.isNotNull("img_path");
                coursesImgModel.isNotNull("img_url");
                coursesImgModel.orderByDesc("mainImg");
                List<CoursesImg> coursesImgList = coursesImgService.list(coursesImgModel);
                courses.setCoursesImgList(coursesImgList);
                if (coursesImgList != null && coursesImgList.size() > 0) {
                    cod.setImageMainPath(coursesImgList.get(0).getImgUrl());
                }
                //--------查询菜品主图结束----------
                cod.setCourseName(courses.getNameCh());
                if (!StringTools.hasText(courses.getNameEn())) {
                    cod.setCourseNameEn(courses.getNameCh());
                }

                QueryWrapper<CourseNutrition> nutModel = new QueryWrapper<>();
                nutModel.eq("recipes_code", courses.getPosNo());
                nutModel.eq("is_delete", false);
                List<CourseNutrition> cn = courseNutritionManager.queryList(nutModel);
                //为每个餐品添加营养信息
                cod.setNutList(cn);
                for (CourseNutrition nutrition : cn) {
                    if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_NL)) {
                        NL = nutrition.getQuantity() * cod.getQuantity();
                        NL = DoubleTools.doubleNumberFormat2(NL);
                        NLTotal += NL;
                        NLTotal = DoubleTools.doubleNumberFormat2(NLTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Kilocalorie", NL);
                        } else {
                            nutMap.put("能量", NL);
                        }

                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_TSHHW)) {
                        TSHHW = nutrition.getQuantity() * cod.getQuantity();
                        TSHHW = DoubleTools.doubleNumberFormat2(TSHHW);
                        CSHHWTotal += TSHHW;
                        CSHHWTotal = DoubleTools.doubleNumberFormat2(CSHHWTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Carbohydrate", TSHHW);
                        } else {
                            nutMap.put("碳水化合物", TSHHW);
                        }

                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_SSXW)) {
                        SSXW = nutrition.getQuantity() * cod.getQuantity();
                        SSXW = DoubleTools.doubleNumberFormat2(SSXW);
                        SSXWTotal += SSXW;
                        SSXWTotal = DoubleTools.doubleNumberFormat2(SSXWTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Sodium", SSXW);
                        } else {
                            nutMap.put("钠", SSXW);
                        }

                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_DBZ)) {
                        DBZ = nutrition.getQuantity() * cod.getQuantity();
                        DBZ = DoubleTools.doubleNumberFormat2(DBZ);
                        DBZTotal += DBZ;
                        DBZTotal = DoubleTools.doubleNumberFormat2(DBZTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Protein", DBZ);
                        } else {
                            nutMap.put("蛋白质", DBZ);
                        }

                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_ZF)) {
                        ZF = nutrition.getQuantity() * cod.getQuantity();
                        ZF = DoubleTools.doubleNumberFormat2(ZF);
                        ZFTotal += ZF;
                        ZFTotal = DoubleTools.doubleNumberFormat2(ZFTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Fats", ZF);
                        } else {
                            nutMap.put("脂肪", ZF);
                        }

                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_XW)) {
                        XW = nutrition.getQuantity() * cod.getQuantity();
                        XW = DoubleTools.doubleNumberFormat2(XW);
                        XWTotal += XW;
                        XWTotal = DoubleTools.doubleNumberFormat2(XWTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Filer", XW);
                        } else {
                            nutMap.put("膳食纤维", XW);
                        }

                    }
                }
                cod.setNutMap(nutMap);
            }
        }

        if (standard==null) {
//            如果表中未查到标准数据则自己计算
            Double memberWeight = member.getWeightId();
            Double memberHeight = member.getHeight();
            //計算對比體重，tempWeight
            Double tempWeight = 0D;
            if (memberHeight > 150) {
                tempWeight = memberHeight - 105;
            } else {
                tempWeight = memberHeight - 100;
            }
            System.out.println("tempWeight:" + tempWeight);
            //對比體重，如果+-10%正常，大了超重小了過瘦
            String flag = "";
            if (memberWeight < tempWeight * 0.9) {
                //过瘦
                flag = "S";
            } else if (memberWeight > tempWeight * 1.1) {
                //过胖
                flag = "P";
            } else {
                //正常
                flag = "ZC";
            }
            System.out.println("flag:" + flag);
            //计算能量四个
            String userAge = member.getUserAge().toString();
            Double userAgeDouble = Double.parseDouble(userAge);
            if (member.getActive().toString().equals("G")) {
                if (flag.equals("S")) {
                    biaozhunNL = tempWeight * 45;
                } else if (flag.equals("ZC")) {
                    biaozhunNL = tempWeight * 40;
                } else {
                    biaozhunNL = tempWeight * 35;
                }
            } else if (member.getActive().toString().equals("Z")) {
                if (flag.equals("S")) {
                    biaozhunNL = tempWeight * 40;
                } else if (flag.equals("ZC")) {
                    biaozhunNL = tempWeight * 35;
                } else {
                    biaozhunNL = tempWeight * 30;
                }
            } else if (member.getActive().toString().equals("L")) {

                if (flag.equals("S")) {
                    biaozhunNL = tempWeight * 35;
                } else if (flag.equals("ZC")) {
                    if (userAgeDouble >= 60) {
                        biaozhunNL = tempWeight * 25;
                    } else {
                        biaozhunNL = tempWeight * 30;
                    }
                } else {
                    biaozhunNL = tempWeight * 20;
                }
            } else {
                if (flag.equals("S")) {
                    biaozhunNL = tempWeight * 30;
                } else if (flag.equals("ZC")) {
                    if (userAgeDouble >= 60) {
                        biaozhunNL = tempWeight * 20;
                    } else {
                        biaozhunNL = tempWeight * 25;
                    }
                } else {
                    biaozhunNL = tempWeight * 20;
                }
            }
            System.out.println("biaozhunNL:" + biaozhunNL);
            //年齡影響
            if (userAgeDouble >= 50 && userAgeDouble < 65) {
                biaozhunNL = biaozhunNL * 0.95;
            } else if (userAgeDouble >= 65 && userAgeDouble < 80) {
                biaozhunNL = biaozhunNL * 0.92;
            } else if (userAgeDouble >= 80) {
                biaozhunNL = biaozhunNL * 0.85;
            }

            //计算蛋白质
            biaozhunDDZ = biaozhunNL * 0.16 / 4;
            //计算脂肪
            biaozhunZF = biaozhunNL * 0.28 / 9;
            //计算碳酸
            biaozhunTS = biaozhunNL * 0.56 / 4;

            //计算钠的
            if (userAgeDouble <= 4) {
                biaozhunNA = 700D;
            } else if (userAgeDouble > 4 && userAgeDouble <= 7) {
                biaozhunNA = 900D;
            } else if (userAgeDouble > 7 && userAgeDouble <= 11) {
                biaozhunNA = 1200D;
            } else if (userAgeDouble > 11 && userAgeDouble <= 14) {
                biaozhunNA = 1400D;
            } else if (userAgeDouble > 14 && userAgeDouble <= 18) {
                biaozhunNA = 1600D;
            } else if (userAgeDouble > 18 && userAgeDouble <= 50) {
                biaozhunNA = 1500D;
            } else if (userAgeDouble > 50 && userAgeDouble <= 65) {
                biaozhunNA = 1400D;
            } else if (userAgeDouble > 65 && userAgeDouble <= 80) {
                biaozhunNA = 1400D;
            } else if (userAgeDouble > 80) {
                biaozhunNA = 1300D;
            }
            System.out.println("biaozhunNA:" + biaozhunNA);
            //膳食纤维永远是30
            biaozhunXW = 30D;
        }



        Map<String, Double> map = new LinkedHashMap<String, Double>();
        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
            map.put("Kilocalorie", NLTotal);
            map.put("Sodium", SSXWTotal);
            map.put("Fiber", XWTotal);
            map.put("Protein", DBZTotal);
            map.put("Fats", ZFTotal);
            map.put("Carbohydrate", CSHHWTotal);
        } else {
            map.put("能量", NLTotal);
            map.put("钠", SSXWTotal);
            map.put("膳食纤维", XWTotal);
            map.put("蛋白质", DBZTotal);
            map.put("脂肪", ZFTotal);
            map.put("碳水化合物", CSHHWTotal);
        }
        List<Double> todayNutData = new ArrayList<>();
        StringBuffer indicator = new StringBuffer();
        Double maxNL = biaozhunNL, maxTS = biaozhunTS, maxDBZ = biaozhunDDZ, maxZF = biaozhunZF, maxXW = biaozhunXW;
        while (NLTotal > maxNL || DBZTotal > maxDBZ || CSHHWTotal > maxTS || ZFTotal > maxZF || XWTotal > maxXW) {
            maxNL = maxNL * 1.2;
            maxDBZ = maxDBZ * 1.2;
            maxTS = maxTS * 1.2;
            maxZF = maxZF * 1.2;
            maxXW = maxXW * 1.2;
        }
        String nlStr = df.format(biaozhunNL);
        String dbzStr = df.format(biaozhunDDZ);
        String tsStr = df.format(biaozhunTS);
        String naStr = df.format(biaozhunNA);
        String zfStr = df.format(biaozhunZF);
        String xwStr = df.format(biaozhunXW);

        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
            indicator.append("[{text:'Kilocalorie\n(" + df.format(maxNL) + "kcal)', max: " + maxNL + "}").append(",");
            indicator.append("{text:'Protein  \n(" + df.format(maxDBZ) + "g)', max: " + maxDBZ + "}").append(",");
            indicator.append("{text:'Carbohydrate\n(" + df.format(maxTS) + "g)', max: " + maxTS + "}").append(",");
            indicator.append("{text:'Fiber\n(" + df.format(maxXW) + "g)', max: " + maxXW + "}").append(",");
            indicator.append("{text:'  Fats\n(" + df.format(maxZF) + "g)', max: " + maxZF + "}]");
            todayNutData.add(NLTotal);
            todayNutData.add(DBZTotal);
            todayNutData.add(CSHHWTotal);
            todayNutData.add(XWTotal);
            todayNutData.add(ZFTotal);

        } else {
            indicator.append("[{text:'能量\r\n(" + df.format(maxNL) + "kcal)', max: " + maxNL + "}").append(",");
            indicator.append("{text:'蛋白质  \n(" + df.format(maxDBZ) + "g)', max: " + maxDBZ + "}").append(",");
            indicator.append("{text:'碳水化合物\n(" + df.format(maxTS) + "g)', max: " + maxTS + "}").append(",");
            indicator.append("{text:'膳食纤维\n(" + df.format(maxXW) + "g)', max: " + maxXW + "}").append(",");
            indicator.append("{text:'   脂肪\n(" + df.format(maxZF) + "g)', max: " + maxZF + "}]");

            todayNutData.add(NLTotal);
            todayNutData.add(DBZTotal);
            todayNutData.add(CSHHWTotal);
            todayNutData.add(XWTotal);
            todayNutData.add(ZFTotal);
        }
        //添加标准值
        List<String> biaoZhunData = new ArrayList<>();
        biaoZhunData.add(nlStr);
        biaoZhunData.add(dbzStr);
        biaoZhunData.add(tsStr);
        biaoZhunData.add(xwStr);
        biaoZhunData.add(zfStr);

        //格式化标准值
        standard.setHot(Double.valueOf(df.format(biaozhunNL)));
        standard.setProtein(Double.valueOf(df.format(biaozhunDDZ)));
        standard.setSodium(Double.valueOf(df.format(biaozhunNA)));
        standard.setFat(Double.valueOf(df.format(biaozhunZF)));
        standard.setCarbon(Double.valueOf(df.format(biaozhunTS)));
        standard.setFiler(Double.valueOf(df.format(biaozhunXW)));

        //雷达图最外层数据
        model.addAttribute("indicator", JSON.parseArray(indicator.toString()));
        //今日摄入营养数据
        model.addAttribute("todayNutData", todayNutData);
        //今日摄入标准数据
        model.addAttribute("biaoZhunData", biaoZhunData);
        model.addAttribute("biaozhun", standard);//每日用标准摄入含身体数据
        model.addAttribute("is_success", true);
        model.addAttribute("map", map);//今日摄入map
        model.addAttribute("list", list);//已支付有效订单
        model.addAttribute("par", par);//区分测算与今日
        model.addAttribute("openid", member.getOpenid());
        model.addAttribute("member", member);
        return JSONObject.toJSONString(model, SerializerFeature.WriteMapNullValue);
    }


    /**
     * 营养测算
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/calculation", method = RequestMethod.GET)
    @ResponseBody
    public String calculationGet(Model model, HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        if (member.getWeightId() == null) {
            return JSON.toJSONString("{is_success:false,messages:'请完善体重信息'}");
        } else if (member.getHeight() == null) {
            return JSON.toJSONString("{is_success:false,messages:'请完善身高信息'}");
        } else if (member.getActive() == null) {
            return JSON.toJSONString("{is_success:false,messages:'请完善活动强度信息'}");
        }

        //查询对应身体参数标准值
        QueryWrapper<Standard> standardModel = new QueryWrapper<>();
        DecimalFormat df = new DecimalFormat("######0.00");
        //--------体重-------
        if (member.getWeightId() != null) {
            standardModel.between("WEIGHT-" + member.getWeightId().intValue(), -1, 1);
        }
        //--------年龄-------
        if (member.getUserAge() != null) {
            standardModel.between("AGE-" + member.getUserAge().intValue(), -1, 1);
        }
        //--------身高-------
        if (member.getHeight() != null) {
            standardModel.between("HEIGHT-" + member.getHeight().intValue(), -1, 1);
        }

        //--------运动强度-------
        if (member.getHeight() != null) {
            standardModel.eq("ACTIVE", member.getActive());
        }

        List<Standard> nutList = standardManager.list(standardModel);
        Standard standard = null;
        if (nutList != null && nutList.size() > 0) {
            standard = nutList.get(0);
        } else {
            standard = new Standard();
            standard.setHot(0.0);
            standard.setProtein(0.0);
            standard.setSodium(0.0);
            standard.setFat(0.0);
            standard.setCarbon(0.0);
            standard.setFiler(0.0);
        }

        model.addAttribute("zhOrEn", Finals.ZhOrEn.values());
        model.addAttribute("member", member);
        Double NL = 0.0, TSHHW = 0.0, SSXW = 0.0, DBZ = 0.0, ZF = 0.0, NLTotal = 0.0, SSXWTotal = 0.0, DBZTotal = 0.0, ZFTotal = 0.0, HHWTotal = 0.0;
        Double biaozhunNL = 0.0, biaozhunDDZ = 0.0, biaozhunNA = 0.0, biaozhunZF = 0.0, biaozhunTS = 0.0, biaozhunXW = 0.0;
        Double XW = 0.0, XWTotal = 0.0;


        //------今日摄入营养---------
        QueryWrapper<CoursesOrdersDetails> queryModel = new QueryWrapper<>();
        queryModel.ge("last_changed", LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
        queryModel.le("last_changed", LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
        queryModel.eq("is_effective", true);
        queryModel.eq("is_refunding", 0);
        queryModel.eq("creator", member.getId());
        List<CoursesOrdersDetails> list = coursesOrdersDetailsManager.queryList(queryModel);
        Courses courses;
        if (list != null && list.size() > 0) {

            //计算今日摄入营养总量
            for (CoursesOrdersDetails cod : list) {
                NL = 0.0;
                TSHHW = 0.0;
                SSXW = 0.0;
                DBZ = 0.0;
                ZF = 0.0;
                Map<String, Double> nutMap = new TreeMap<String, Double>(new Comparator<String>() {
                    @Override
                    public int compare(String obj1, String obj2) {
                        return obj1.compareTo(obj2);
                    }
                });
                if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                    nutMap.put("Kilocalorie", 0.0);
                    nutMap.put("Sodium", 0.0);
                    nutMap.put("Protein", 0.0);
                    nutMap.put("Fats", 0.0);
                    nutMap.put("Carbohydrate", 0.0);
                } else {
                    nutMap.put("能量", 0.0);
                    nutMap.put("钠", 0.0);
                    nutMap.put("蛋白质", 0.0);
                    nutMap.put("脂肪", 0.0);
                    nutMap.put("碳水化合物", 0.0);
                }

                QueryWrapper<CourseNutrition> nutModel = new QueryWrapper<>();
                courses = coursesManager.findById(cod.getCourseId());
                //--------查询菜品主图开始----------
                QueryWrapper<CoursesImg> coursesImgModel = new QueryWrapper<>();
                coursesImgModel.eq("course_pos_no", courses.getPosNo());
                coursesImgModel.isNotNull("img_path");
                coursesImgModel.isNotNull("img_url");
                coursesImgModel.orderByDesc("mainImg");
                List<CoursesImg> coursesImgList = coursesImgService.list(coursesImgModel);
                courses.setCoursesImgList(coursesImgList);
                if (coursesImgList != null && coursesImgList.size() > 0) {
                    cod.setImageMainPath(coursesImgList.get(0).getImgUrl());
                }
                //--------查询菜品主图结束----------

                cod.setCourseName(courses.getNameCh());
                if (!StringTools.hasText(courses.getNameEn())) {
                    cod.setCourseNameEn(courses.getNameCh());
                }
                nutModel.eq("recipes_code", courses.getPosNo());
                nutModel.eq("is_delete", false);
                List<CourseNutrition> cn = courseNutritionManager.queryList(nutModel);
                //为每个餐品添加营养信息
                cod.setNutList(cn);
                for (int i = 0; i < cn.size(); i++) {
                    CourseNutrition nutrition = cn.get(i);
                    if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_NL)) {
                        NL = nutrition.getQuantity() * cod.getQuantity();
                        NL = DoubleTools.doubleNumberFormat2(NL);
                        NLTotal += NL;
                        NLTotal = DoubleTools.doubleNumberFormat2(NLTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Kilocalorie", NL);
                        } else {
                            nutMap.put("能量", NL);
                        }

                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_TSHHW)) {
                        TSHHW = nutrition.getQuantity() * cod.getQuantity();
                        TSHHW = DoubleTools.doubleNumberFormat2(TSHHW);
                        HHWTotal += TSHHW;
                        HHWTotal = DoubleTools.doubleNumberFormat2(HHWTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Carbohydrate", TSHHW);
                        } else {
                            nutMap.put("碳水化合物", TSHHW);
                        }

                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_SSXW)) {
                        SSXW = nutrition.getQuantity() * cod.getQuantity();
                        SSXW = DoubleTools.doubleNumberFormat2(SSXW);
                        SSXWTotal += SSXW;
                        SSXWTotal = DoubleTools.doubleNumberFormat2(SSXWTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Sodium", SSXW);
                        } else {
                            nutMap.put("钠", SSXW);
                        }

                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_DBZ)) {
                        DBZ = nutrition.getQuantity() * cod.getQuantity();
                        DBZ = DoubleTools.doubleNumberFormat2(DBZ);
                        DBZTotal += DBZ;
                        DBZTotal = DoubleTools.doubleNumberFormat2(DBZTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Protein", DBZ);
                        } else {
                            nutMap.put("蛋白质", DBZ);
                        }

                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_ZF)) {
                        ZF = nutrition.getQuantity() * cod.getQuantity();
                        ZF = DoubleTools.doubleNumberFormat2(ZF);
                        ZFTotal += ZF;
                        ZFTotal = DoubleTools.doubleNumberFormat2(ZFTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Fats", ZF);
                        } else {
                            nutMap.put("脂肪", ZF);
                        }

                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_XW)) {
                        XW = nutrition.getQuantity() * cod.getQuantity();
                        XW = DoubleTools.doubleNumberFormat2(XW);
                        XWTotal += XW;
                        XWTotal = DoubleTools.doubleNumberFormat2(XWTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Filer", XW);
                        } else {
                            nutMap.put("膳食纤维", XW);
                        }

                    }
                }
                cod.setNutMap(nutMap);
            }
        } else {
            biaozhunNL = standard.getHot();
            biaozhunDDZ = standard.getProtein();
            biaozhunNA = standard.getSodium();
            biaozhunZF = standard.getFat();
            biaozhunTS = standard.getCarbon();
            biaozhunXW = standard.getFiler();
        }
        //今日已摄入营养
        Map<String, Double> map = new LinkedHashMap<String, Double>();
        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
            map.put("Kilocalorie", NLTotal);
            map.put("Sodium", SSXWTotal);
            map.put("Fiber", XWTotal);
            map.put("Protein", DBZTotal);
            map.put("Fats", ZFTotal);
            map.put("Carbohydrate", HHWTotal);
        } else {
            map.put("能量", NLTotal);
            map.put("钠", SSXWTotal);
            map.put("膳食纤维", XWTotal);
            map.put("蛋白质", DBZTotal);
            map.put("脂肪", ZFTotal);
            map.put("碳水化合物", HHWTotal);
        }

        //------营养测算---------
        Double csNL = 0.0, csTSHHW = 0.0, csSSXW = 0.0, csDBZ = 0.0, csZF = 0.0, csNLTotal = 0.0, csSSXWTotal = 0.0, csDBZTotal = 0.0, csZFTotal = 0.0, csHHWTotal = 0.0, csXW = 0.0, csXWTotal = 0.0;
        QueryWrapper<CoursesOrdersDetails> queryModel2 = new QueryWrapper<>();
        queryModel2.ge("last_changed", LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
        queryModel2.le("last_changed", LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
        queryModel2.eq("is_effective", false);
        queryModel2.eq("is_refunding", 0);
        queryModel2.eq("creator", member.getId());
        List<CoursesOrdersDetails> cslist = coursesOrdersDetailsManager.queryList(queryModel2);
        if (cslist != null && cslist.size() > 0) {
            for (CoursesOrdersDetails cod : cslist) {
                csNL = 0.0;
                csTSHHW = 0.0;
                csSSXW = 0.0;
                csDBZ = 0.0;
                csZF = 0.0;
                Map<String, Double> nutMap = new TreeMap<String, Double>(new Comparator<String>() {
                    @Override
                    public int compare(String obj1, String obj2) {
                        return obj1.compareTo(obj2);
                    }
                });
                if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                    cod.setCourseName(cod.getCourse().getNameEn());
                    nutMap.put("Kilocalorie", 0.0);
                    nutMap.put("Sodium", 0.0);
                    nutMap.put("Protein", 0.0);
                    nutMap.put("Fats", 0.0);
                    nutMap.put("Carbohydrate", 0.0);
                } else {
                    cod.setCourseName(cod.getCourse().getNameCh());
                    nutMap.put("能量", 0.0);
                    nutMap.put("钠", 0.0);
                    nutMap.put("蛋白质", 0.0);
                    nutMap.put("脂肪", 0.0);
                    nutMap.put("碳水化合物", 0.0);
                }

                QueryWrapper<CourseNutrition> nutModel = new QueryWrapper<>();
                courses = coursesManager.findById(cod.getCourseId());
                //--------查询菜品主图开始----------
                QueryWrapper<CoursesImg> coursesImgModel = new QueryWrapper<>();
                coursesImgModel.eq("course_pos_no", courses.getPosNo());
                coursesImgModel.isNotNull("img_path");
                coursesImgModel.isNotNull("img_url");
                coursesImgModel.orderByDesc("mainImg");
                List<CoursesImg> coursesImgList = coursesImgService.list(coursesImgModel);
                courses.setCoursesImgList(coursesImgList);
                if (coursesImgList != null && coursesImgList.size() > 0) {
                    cod.setImageMainPath(coursesImgList.get(0).getImgUrl());
                }
                //--------查询菜品主图结束----------

                nutModel.eq("recipes_code", courses.getPosNo());
                nutModel.eq("is_delete", false);
                List<CourseNutrition> cn = courseNutritionManager.queryList(nutModel);
                //为每个餐品添加营养信息
                cod.setNutList(cn);
                for (int i = 0; i < cn.size(); i++) {
                    CourseNutrition nutrition = cn.get(i);
                    if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_NL)) {
                        csNL = nutrition.getQuantity() * cod.getQuantity();
                        csNL = DoubleTools.doubleNumberFormat2(csNL);
                        csNLTotal += csNL;
                        csNLTotal = DoubleTools.doubleNumberFormat2(csNLTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Kilocalorie", csNL);
                        } else {
                            nutMap.put("能量", csNL);
                        }

                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_TSHHW)) {
                        csTSHHW = nutrition.getQuantity() * cod.getQuantity();
                        csTSHHW = DoubleTools.doubleNumberFormat2(csTSHHW);
                        csHHWTotal += csTSHHW;
                        csHHWTotal = DoubleTools.doubleNumberFormat2(csHHWTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Carbohydrate", csTSHHW);
                        } else {
                            nutMap.put("碳水化合物", csTSHHW);
                        }

                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_SSXW)) {
                        csSSXW = nutrition.getQuantity() * cod.getQuantity();
                        csSSXW = DoubleTools.doubleNumberFormat2(csSSXW);
                        csSSXWTotal += csSSXW;
                        csSSXWTotal = DoubleTools.doubleNumberFormat2(csSSXWTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Sodium", csSSXW);
                        } else {
                            nutMap.put("钠", csSSXW);
                        }

                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_DBZ)) {
                        csDBZ = nutrition.getQuantity() * cod.getQuantity();
                        csDBZ = DoubleTools.doubleNumberFormat2(csDBZ);
                        csDBZTotal += csDBZ;
                        csDBZTotal = DoubleTools.doubleNumberFormat2(csDBZTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Protein", csDBZ);
                        } else {
                            nutMap.put("蛋白质", csDBZ);
                        }
                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_ZF)) {
                        csZF = nutrition.getQuantity() * cod.getQuantity();
                        csZF = DoubleTools.doubleNumberFormat2(csZF);
                        csZFTotal += csZF;
                        csZFTotal = DoubleTools.doubleNumberFormat2(csZFTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Fats", csZF);
                        } else {
                            nutMap.put("脂肪", csZF);
                        }
                    } else if (nutrition.getNutritionCode().equals(Finals.NUT_CODE_XW)) {
                        csXW = nutrition.getQuantity() * cod.getQuantity();
                        csXW = DoubleTools.doubleNumberFormat2(csXW);
                        csXWTotal += csXW;
                        csXWTotal = DoubleTools.doubleNumberFormat2(csXWTotal);
                        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
                            nutMap.put("Filer", csXW);
                        } else {
                            nutMap.put("膳食纤维", csXW);
                        }

                    }
                }
                cod.setNutMap(nutMap);
            }
        }

        Double memberWeight = member.getWeightId();
        Double memberHeight = member.getHeight();
        //計算對比體重，tempWeight
        Double tempWeight = 0D;
        if (memberHeight > 150) {
            tempWeight = memberHeight - 105;
        } else {
            tempWeight = memberHeight - 100;
        }
        System.out.println("tempWeight:" + tempWeight);
        //對比體重，如果+-10%正常，大了超重小了過瘦
        String flag = "";
        if (memberWeight < tempWeight * 0.9) {
            //过瘦
            flag = "S";
        } else if (memberWeight > tempWeight * 1.1) {
            //过胖
            flag = "P";
        } else {
            //正常
            flag = "ZC";
        }
        System.out.println("flag:" + flag);
        //计算能量四个
        String userAge = member.getUserAge().toString();
        Double userAgeDouble = Double.parseDouble(userAge);
        if (member.getActive().toString().equals("G")) {
            if (flag.equals("S")) {
                biaozhunNL = tempWeight * 45;
            } else if (flag.equals("ZC")) {
                biaozhunNL = tempWeight * 40;
            } else {
                biaozhunNL = tempWeight * 35;
            }
        } else if (member.getActive().toString().equals("Z")) {
            if (flag.equals("S")) {
                biaozhunNL = tempWeight * 40;
            } else if (flag.equals("ZC")) {
                biaozhunNL = tempWeight * 35;
            } else {
                biaozhunNL = tempWeight * 30;
            }
        } else if (member.getActive().toString().equals("L")) {

            if (flag.equals("S")) {
                biaozhunNL = tempWeight * 35;
            } else if (flag.equals("ZC")) {
                if (userAgeDouble >= 60) {
                    biaozhunNL = tempWeight * 25;
                } else {
                    biaozhunNL = tempWeight * 30;
                }
            } else {
                biaozhunNL = tempWeight * 20;
            }
        } else {
            if (flag.equals("S")) {
                biaozhunNL = tempWeight * 30;
            } else if (flag.equals("ZC")) {
                if (userAgeDouble >= 60) {
                    biaozhunNL = tempWeight * 20;
                } else {
                    biaozhunNL = tempWeight * 25;
                }
            } else {
                biaozhunNL = tempWeight * 20;
            }
        }
        //年齡影響
        if (userAgeDouble >= 50 && userAgeDouble < 65) {
            biaozhunNL = biaozhunNL * 0.95;
        } else if (userAgeDouble >= 65 && userAgeDouble < 80) {
            biaozhunNL = biaozhunNL * 0.92;
        } else if (userAgeDouble >= 80) {
            biaozhunNL = biaozhunNL * 0.85;
        }
        biaozhunDDZ = biaozhunNL * 0.16 / 4;
        biaozhunZF = biaozhunNL * 0.28 / 9;
        biaozhunTS = biaozhunNL * 0.56 / 4;
        //计算钠的
        if (userAgeDouble <= 4) {
            biaozhunNA = 700D;
        } else if (userAgeDouble > 4 && userAgeDouble <= 7) {
            biaozhunNA = 900D;
        } else if (userAgeDouble > 7 && userAgeDouble <= 11) {
            biaozhunNA = 1200D;
        } else if (userAgeDouble > 11 && userAgeDouble <= 14) {
            biaozhunNA = 1400D;
        } else if (userAgeDouble > 14 && userAgeDouble <= 18) {
            biaozhunNA = 1600D;
        } else if (userAgeDouble > 18 && userAgeDouble <= 50) {
            biaozhunNA = 1500D;
        } else if (userAgeDouble > 50 && userAgeDouble <= 65) {
            biaozhunNA = 1400D;
        } else if (userAgeDouble > 65 && userAgeDouble <= 80) {
            biaozhunNA = 1400D;
        } else if (userAgeDouble > 80) {
            biaozhunNA = 1300D;
        }
        System.out.println("biaozhunNA:" + biaozhunNA);
        //膳食纤维永远是30
        biaozhunXW = 30D;

        List<Double> todayNutData = new ArrayList<>();
        StringBuffer indicator = new StringBuffer();
        Double maxNL = biaozhunNL, maxTS = biaozhunTS, maxDBZ = biaozhunDDZ, maxZF = biaozhunZF, maxXW = biaozhunXW;
        while ((NLTotal + csNLTotal) > maxNL || (DBZTotal + csDBZTotal) > maxDBZ || (HHWTotal + csHHWTotal) > maxTS || (ZFTotal + csZFTotal) > maxZF || (XWTotal + csXWTotal) > maxXW) {
            maxNL = maxNL * 1.2;
            maxDBZ = maxDBZ * 1.2;
            maxTS = maxTS * 1.2;
            maxZF = maxZF * 1.2;
            maxXW = maxXW * 1.2;
        }
        String nlStr = df.format(biaozhunNL);
        String dbzStr = df.format(biaozhunDDZ);
        String tsStr = df.format(biaozhunTS);
        String naStr = df.format(biaozhunNA);
        String zfStr = df.format(biaozhunZF);
        String xwStr = df.format(biaozhunXW);

        if (Finals.ZhOrEn.E.equals(member.getZhOrEn())) {
            indicator.append("[{text:'Kilocalorie(" + df.format(maxNL) + ")', max: " + maxNL + "}").append(",");
            indicator.append("{text:'Protein(" + df.format(maxDBZ) + ")', max: " + maxDBZ + "}").append(",");
            indicator.append("{text:'Carbohydrate(" + df.format(maxTS) + ")', max: " + maxTS + "}").append(",");
            indicator.append("{text:'Fiber(" + df.format(maxXW) + ")', max: " + maxXW + "}").append(",");
            indicator.append("{text:'Fats(" + df.format(maxZF) + ")', max: " + maxZF + "}]");
            todayNutData.add(NLTotal);
            todayNutData.add(DBZTotal);
            todayNutData.add(HHWTotal);
            todayNutData.add(XWTotal);
            todayNutData.add(ZFTotal);

        } else {
            indicator.append("[{text:'能量(" + df.format(maxNL) + ")', max: " + maxNL + "}").append(",");
            indicator.append("{text:'蛋白质(" + df.format(maxDBZ) + ")', max: " + maxDBZ + "}").append(",");
            indicator.append("{text:'碳水化合物(" + df.format(maxTS) + ")', max: " + maxTS + "}").append(",");
            indicator.append("{text:'膳食纤维(" + df.format(maxXW) + ")', max: " + maxXW + "}").append(",");
            indicator.append("{text:'脂肪(" + df.format(maxZF) + ")', max: " + maxZF + "}]");

            todayNutData.add(NLTotal + csNLTotal);
            todayNutData.add(DBZTotal + csDBZTotal);
            todayNutData.add(HHWTotal + csHHWTotal);
            todayNutData.add(XWTotal + csXWTotal);
            todayNutData.add(ZFTotal + csZFTotal);
        }
        //添加标准值
        List<String> biaoZhunData = new ArrayList<>();
        biaoZhunData.add(nlStr);
        biaoZhunData.add(dbzStr);
        biaoZhunData.add(tsStr);
        biaoZhunData.add(xwStr);
        biaoZhunData.add(zfStr);

        //格式化标准值
        standard.setHot(Double.valueOf(df.format(biaozhunNL)));
        standard.setProtein(Double.valueOf(df.format(biaozhunDDZ)));
        standard.setSodium(Double.valueOf(df.format(biaozhunNA)));
        standard.setFat(Double.valueOf(df.format(biaozhunZF)));
        standard.setCarbon(Double.valueOf(df.format(biaozhunTS)));
        standard.setFiler(Double.valueOf(df.format(biaozhunXW)));


        model.addAttribute("biaozhun", standard);//每日用标准摄入
        model.addAttribute("indicator", JSON.parseArray(indicator.toString()));
        model.addAttribute("todayNutData", todayNutData);
        model.addAttribute("biaoZhunData", biaoZhunData);
        model.addAttribute("is_success", true);
        model.addAttribute("map", map);
        cslist.addAll(list);
        model.addAttribute("list", cslist);
        model.addAttribute("openid", member.getOpenid());
        return JSONObject.toJSONString(model, SerializerFeature.WriteMapNullValue);
    }


    /**
     * 两周营养分析
     *
     * @param model
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/twoZhou", method = RequestMethod.GET)
    @ResponseBody
    public String zhouGet(Model model, HttpServletRequest request) throws Exception {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);

        model.addAttribute("member", member);
        model.addAttribute("zhOrEn", Finals.ZhOrEn.values());
        Map<String, Double> map = new TreeMap<String, Double>(
                new Comparator<String>() {
                    @Override
                    public int compare(String obj1, String obj2) {
                        // 降序排序
                        return obj2.compareTo(obj1);
                    }
                });

        QueryWrapper<Standard> standardModel = new QueryWrapper<>();
        DecimalFormat df = new DecimalFormat("######0.00");
        //--------体重-------
        if (member.getWeightId() != null) {
            standardModel.between("WEIGHT-" + member.getWeightId().intValue(), -1, 1);
        }
        //--------年龄-------
        if (member.getUserAge() != null) {
            standardModel.between("AGE-" + member.getUserAge().intValue(), -1, 1);
        }
        //--------身高-------
        if (member.getHeight() != null) {
            standardModel.between("HEIGHT-" + member.getHeight().intValue(), -1, 1);
        }

        //--------运动强度-------
        if (member.getHeight() != null) {
            standardModel.eq("ACTIVE", member.getActive());
        }

        List<Standard> nutList = standardManager.list(standardModel);
        Standard standard = null;
        if (nutList != null && nutList.size() > 0) {
            standard = nutList.get(0);
        } else {
            standard = new Standard();
            standard.setHot(2600.0);
            standard.setProtein(58.0);
            standard.setSodium(1600.0);
            standard.setFat(82.0);
            standard.setCarbon(420.0);
        }



        Double hot = 0.0;
        DateTimeFormatter sim = DateTimeFormatter.ofPattern("MM-dd");
        ArrayList<String> x = new ArrayList<>();
        List<String> timeList = new ArrayList<String>();
        String timeStr = "";

        LocalDate startDate = LocalDate.now();
        LocalDate endDate = LocalDate.now().plusDays(1);
        //查询过去13天摄入能量
        for (int i = 13; i > 0; i--) {
            startDate = startDate.minusDays(1);
            endDate = endDate.minusDays(1);
            timeStr = sim.format(startDate);
            x.add(timeStr);
            timeList.add(timeStr);
            List<OrderOfDaynut> list = orderOfDaynutManager.query().eq("member_id", member.getId()).ge("con_time", startDate).le("con_time", endDate).list();
            if (list.size() > 0) {
                for (OrderOfDaynut dayNut : list) {
                    List<CourseNutrition> courseNutritionList = courseNutritionManager.query().eq("recipes_code", dayNut.getResourseCode())
                            .eq("nutrition_code", "NA01")
                            .eq("is_delete", "0")
                            .orderByDesc("last_changed_time").list();
                    if (null != courseNutritionList && courseNutritionList.size() > 0) {
                        if (map.containsKey(sim.format(dayNut.getConTime()))) {
                            Double old = map.get(sim.format(dayNut.getConTime()));
                            Double newSize = old + courseNutritionList.get(0).getQuantity();
                            DoubleTools.doubleNumberFormat2(newSize);
                            map.remove(sim.format(dayNut.getConTime()));
                            map.put(sim.format(dayNut.getConTime()), newSize);
                        } else {
                            map.put(sim.format(dayNut.getConTime()), courseNutritionList.get(0).getQuantity());
                        }
                    }
                }
            } else {
                map.put(timeStr, 0.00);
            }

        }

        //计算今日摄入能量
        String todayStr = sim.format(startDate);
        x.add(todayStr);
        StringBuilder y = new StringBuilder();
        y.append("[");
        for (int k = 0; k < timeList.size(); k++) {
//            if (map.containsKey(timeList.get(k))) {
            y.append(map.get(timeList.get(k)));
            y.append(",");
//            }
        }
        Double todayNl = 0.0;
        QueryWrapper<CoursesOrdersDetails> queryModel = new QueryWrapper<>();
        queryModel.lt("last_changed", LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
        queryModel.gt("last_changed", LocalDate.now());
        queryModel.eq("is_effective", "1");
        queryModel.eq("is_refunding", 0);
        queryModel.eq("creator", member.getId());
        //查询今日有效订单
        List<CoursesOrdersDetails> list = coursesOrdersDetailsManager.queryList(queryModel);
        if (list != null && list.size() > 0) {
            for (CoursesOrdersDetails coursesOrdersDetails : list) {
                if (!CoursesOrders.PayWay.CK.equals(coursesOrdersDetails.getMainOrder().getPayWay())) {
                    Courses courses = coursesManager.findById(coursesOrdersDetails.getCourseId());
                    if (courses != null) {
                        QueryWrapper<CourseNutrition> querModel = new QueryWrapper<>();
                        querModel.eq("recipes_code", courses.getPosNo());
                        querModel.eq("nutrition_code", "NA01");
                        querModel.eq("is_delete", false);
                        List<CourseNutrition> courseNutritionList = courseNutritionManager.list(querModel);
                        if (courseNutritionList != null && courseNutritionList.size() > 0) {
                            todayNl += coursesOrdersDetails.getQuantity() * courseNutritionList.get(0).getQuantity();
                        }
                        if (null != standard) {
                            if (Finals.CANCI_ZAO.equals(courses.getMealTimeCode()) || Finals.CANCI_WAN.equals(courses.getMealTimeCode())) {
                                hot += standard.getHot() * 0.3;
                            }
                            if (Finals.CANCI_WU.equals(courses.getMealTimeCode())) {
                                hot += standard.getHot() * 0.4;
                            }
                        }

                    }


                }
            }
            hot = hot / list.size();
        }
        SchoolBaseInfo schoolBaseInfo = schoolBaseInfoService.getById(member.getSchoolId());
        if ("1".equals(schoolBaseInfo.getHasPos())) {
            HttpUtil send = new HttpUtil(kongxc_pos_http_server_url);
            ObjectToXML toXml = new ObjectToXML();
            String uuid = UUID.randomUUID().toString().replace("-", "");

            String searchStart = TimeTools.localDate2String(LocalDate.now(), TimeTools.DAY_FORMAT);
            String searchEnd = TimeTools.localDate2String(LocalDate.now(), TimeTools.DAY_FORMAT);

            String requestConsumerXml = toXml.requestConsumptionRecord(PROPASS, CUS_NAME, member.getSchool().getCode(), member.getIdNumber(), member.getZfPasswd(), searchStart, searchEnd, uuid);
            String responseConsumerXML = send.sendToBoss(requestConsumerXml);

            if ("0000".equals(toXml.resolveReponseConsumptionRecord(responseConsumerXML, request))) {
                List<CardConsumptionModel> consumptionList = (List<CardConsumptionModel>) request.getAttribute("conList");

                if (consumptionList != null && consumptionList.size() > 0) {
                    for (CardConsumptionModel cardConsumptionModel : consumptionList) {
                        Courses courses = coursesManager.findByProperty("pos_no", cardConsumptionModel.getFoodCode());
                        if (courses != null) {
                            QueryWrapper<CourseNutrition> querModel = new QueryWrapper<>();
                            querModel.eq("recipes_code", courses.getPosNo());
                            querModel.eq("nutrition_code", "NA01");
                            querModel.eq("is_delete", false);
                            List<CourseNutrition> courseNutritionList = courseNutritionManager.queryList(querModel);
                            if (courseNutritionList != null && courseNutritionList.size() > 0) {
                                todayNl += Integer.parseInt(cardConsumptionModel.getQuantity()) * courseNutritionList.get(0).getQuantity();

                            }
                            if (null != standard) {

                                if (Finals.CANCI_ZAO.equals(courses.getMealTimeCode()) || Finals.CANCI_WAN.equals(courses.getMealTimeCode())) {
                                    hot += standard.getHot() * 0.3;
                                }
                                if (Finals.CANCI_WU.equals(courses.getMealTimeCode())) {
                                    hot += standard.getHot() * 0.4;
                                }
                            }
                        }
                    }
                    hot = hot / consumptionList.size();
                }
            }

        }
        y.append(todayNl);
        y.append("]");

        map.put(sim.format(LocalDate.now()), todayNl);

        StringBuilder biaoZhunX = new StringBuilder();
        biaoZhunX.append("[");

        for (int i = 14; i > 0; i--) {
            biaoZhunX.append("\'");
            biaoZhunX.append(df.format(standard.getHot()));
            biaoZhunX.append("\',");

        }
        biaoZhunX.setLength(biaoZhunX.length() - 1);
        biaoZhunX.append("]");
        String[] split = biaoZhunX.toString().substring(1, biaoZhunX.length() - 1).replaceAll("'", "").split(",");
        model.addAttribute("biaoZhunX", Arrays.asList(split));
        model.addAttribute("hot", hot);
        model.addAttribute("y", y);
        model.addAttribute("x", x);
        model.addAttribute("map", map.values());
        return JSONObject.toJSONString(model, SerializerFeature.WriteMapNullValue);
    }


    /**
     * BMI记录
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/BMIHistory", method = RequestMethod.POST)
    @ResponseBody
    public String bmiHistory(Model model, HttpServletRequest request, HttpServletResponse response) throws ParseException {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);

        ArrayList<LocalDate> x = new ArrayList<>();
        ArrayList<Double> y = new ArrayList<>();
        Map<LocalDate, Double> map = new HashMap<>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

        String times = request.getParameter("Times");
        Date date = sdf.parse(times);
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate localDate = date.toInstant().atZone(zoneId).toLocalDate();
        for (int i = 1; i <= localDate.lengthOfMonth(); i++) {
            LocalDate localDate1 = localDate.withDayOfMonth(i);
            if (localDate1.isAfter(localDate.now())) break;
            if (localDate1.isAfter(member.getRegisterTime().toLocalDate())) {
                QueryWrapper<MemberBmi> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("member_id", member.getId());
                queryWrapper.gt("creat_time", localDate1);
                queryWrapper.lt("creat_time", LocalDateTime.of(localDate1, LocalTime.MAX));
                List<MemberBmi> list = memberBmiService.list(queryWrapper);
                if (list.size() > 0) {
                    x.add(localDate1);
                    y.add(list.get(0).getBmi());
                    map.put(localDate, list.get(0).getBmi());
                } else if (i > 1) {
                    x.add(localDate1);
                    y.add(y.get(i - 2));
                    map.put(localDate1, y.get(i - 2));
                } else {
                    x.add(localDate1);
                    y.add(0.00);
                    map.put(localDate1, 0.00);
                }
            } else {
                x.add(localDate1);
                y.add(0.00);

                map.put(localDate1, 0.00);
            }

        }
        model.addAttribute("x", x);
        model.addAttribute("y", y);
        model.addAttribute("map", map);
        return JSONObject.toJSONString(model, SerializerFeature.WriteMapNullValue);
    }


    /**
     * 营养菜品推荐
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/recommend", method = RequestMethod.GET)
    @ResponseBody
    public String recommendGet(Model model, HttpServletRequest request) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);

        String type = request.getParameter("Type");
        model.addAttribute("school", member.getSchool());
        model.addAttribute("openid", member.getOpenid());
        List<Courses> yycpList = new ArrayList<>();
        List<CourseNutrition> cn = new ArrayList<>();
        //今日菜单
        QueryWrapper<Courses> coursesModel = new QueryWrapper<>();
        coursesModel.eq("is_delete", false);//未删除
        coursesModel.eq("school_id", member.getSchoolId());
//		coursesModel.eq("restaurant_id",member.getRestaurant().getId());
        coursesModel.ge("startTime", LocalDate.now());
        coursesModel.le("endTime", LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
        List<Courses> courses = coursesManager.list(coursesModel);
        if (courses != null && courses.size() > 0) {
            for (Courses co : courses) {
                //--------查询菜品主图开始----------
                QueryWrapper<CoursesImg> coursesImgModel = new QueryWrapper<>();
                coursesImgModel.eq("course_pos_no", co.getPosNo());
                coursesImgModel.isNotNull("img_path");
                coursesImgModel.isNotNull("img_url");
                coursesImgModel.orderByDesc("mainImg");
                List<CoursesImg> coursesImgList = coursesImgService.list(coursesImgModel);
                co.setCoursesImgList(coursesImgList);
                if (coursesImgList != null && coursesImgList.size() > 0) {
                    co.setImageMainPath(coursesImgList.get(0).getImgUrl());
                }
                //--------查询菜品主图结束----------
                QueryWrapper<CourseNutrition> nutModel = new QueryWrapper<>();
                nutModel.eq("recipes_code", co.getPosNo());
                nutModel.eq("is_delete", false);
                List<CourseNutrition> list = courseNutritionManager.queryList(nutModel);
                co.setCnList(list);
                if ("dz".equals(type)) {
                    nutModel.eq("tagLogo", "dz.png");
                } else if ("dk".equals(type)) {
                    nutModel.eq("tagLogo", "dk.png");
                } else if ("dy".equals(type)) {
                    nutModel.eq("tagLogo", "dy.png");
                } else if ("gw".equals(type)) {
                    nutModel.eq("tagLogo", "gw.png");
                }
                cn = courseNutritionManager.queryList(nutModel);
                if (cn != null && cn.size() > 0) {
                    yycpList.add(co);
                }
            }
        }
        model.addAttribute("member", member);
        model.addAttribute("zhOrEn", Finals.ZhOrEn.values());
        model.addAttribute("yycpList", yycpList);
        return JSONObject.toJSONString(model, SerializerFeature.WriteMapNullValue);
    }


    /**
     * 菜品推荐--不带营养标签的菜品推荐(厨师长推荐)
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/ChefRecommend", method = RequestMethod.GET)
    @ResponseBody
    public String recommend2(Model model, HttpServletRequest request) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);

        //今日菜单
        QueryWrapper<Courses> coursesModel = new QueryWrapper<>();
        coursesModel.eq("is_delete", false);//未删除
        coursesModel.eq("school_id", member.getSchoolId());
        coursesModel.eq("is_top", "1");//推荐菜
        coursesModel.eq("is_stop", "0");
        coursesModel.ge("startTime", LocalDate.now());
        coursesModel.le("endTime", LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
        List<Courses> list = coursesManager.list(coursesModel);
        for (Courses course : list) {
            //--------查询菜品主图开始----------
            QueryWrapper<CoursesImg> coursesImgModel = new QueryWrapper<>();
            coursesImgModel.eq("course_pos_no", course.getPosNo());
            coursesImgModel.isNotNull("img_path");
            coursesImgModel.isNotNull("img_url");
            coursesImgModel.orderByDesc("mainImg");
            List<CoursesImg> coursesImgList = coursesImgService.list(coursesImgModel);
            course.setCoursesImgList(coursesImgList);
            if (coursesImgList != null && coursesImgList.size() > 0) {
                course.setImageMainPath(coursesImgList.get(0).getImgUrl());
            }
            //--------查询菜品主图结束----------
        }
        model.addAttribute("list", list);
        model.addAttribute("member", member);
        return JSONObject.toJSONString(model);
    }
}
